import os
import time
import traceback

import pandas as pd
from aiohttp import web

from script.load_script import  load_model,load_model_re
from utils import ConstValues
from utils.ResponseUtils import toResponse
import asyncio
import uvloop
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
scoreRouter = web.RouteTableDef()


@scoreRouter.post("/score/json")
async def get_single_score(request):
    timeStamp = (str)(time.time())
    request_json = await request.json()
    orderIds = await getOrderIdListFromJson(request_json)
    try:
        data = pd.DataFrame(request_json)
        data.to_csv(timeStamp + ".csv", encoding='gbk')
        score_card = load_model(pd.read_csv(timeStamp + ".csv", encoding='gbk'))
        await removeFile(timeStamp + ".csv")
        return web.json_response(
            toResponse(code=ConstValues.CODE_SUCCESS, message=ConstValues.MESSAGE_SUCCESS,
                       data=score_card))

    except:
        f = open('异常日志.txt', 'a')
        traceback.print_exc(file=f)
        f.flush()
        f.close()
        return web.json_response(
            toResponse(code=ConstValues.CODE_ERROR, message=ConstValues.MESSAGE_ERROR,
                       data=orderIds))




@scoreRouter.post("/rescore/json")
async def get_single_score(request):
    timeStamp = (str)(time.time())
    request_json = await request.json()
    orderIds = await getOrderIdListFromJson(request_json)
    try:
        data = pd.DataFrame(request_json)
        data.to_csv(timeStamp + ".csv", encoding='gbk')
        score_card = load_model_re(pd.read_csv(timeStamp + ".csv", encoding='gbk'))
        await removeFile(timeStamp + ".csv")
        return web.json_response(
            toResponse(code=ConstValues.CODE_SUCCESS, message=ConstValues.MESSAGE_SUCCESS,
                       data=score_card))


    except:
        f = open('异常日志.txt', 'a')
        traceback.print_exc(file=f)
        f.flush()
        f.close()
        return web.json_response(
            toResponse(code=ConstValues.CODE_ERROR, message=ConstValues.MESSAGE_ERROR,
                       data=orderIds))


@scoreRouter.post("/score/file")
async def get_multi_score(request):
    timeStamp = (str)(time.time())
    try:
        reader = await request.multipart()
        file = await reader.next()
        fileName =  timeStamp + ".csv"
        size = 0
        with open(os.path.join('../script/', fileName), 'wb') as f:
            while True:
                chunk = await file.read_chunk()  # 默认是8192个字节。
                if not chunk:
                    break
                size += len(chunk)
                f.write(chunk)
        data = pd.read_csv(fileName, encoding='gbk')
        orderList = await getOrderIdListFromFile(data['订单号'])
        score_card = load_model(data)
        await removeFile(fileName)
        return web.json_response(
            toResponse(code=ConstValues.CODE_SUCCESS, message=ConstValues.MESSAGE_SUCCESS,
                       data=score_card))




    except:
        f = open('异常日志.txt', 'a')
        traceback.print_exc(file=f)
        f.flush()
        f.close()
        return web.json_response(
            toResponse(code=ConstValues.CODE_ERROR, message=ConstValues.MESSAGE_ERROR,
                       data=orderList))

@scoreRouter.post("/rescore/file")
async def get_multi_score(request):
    timeStamp = (str)(time.time())
    try:
        reader = await request.multipart()
        file = await reader.next()
        fileName =  timeStamp + ".csv"
        size = 0
        with open(os.path.join('../script/', fileName), 'wb') as f:
            while True:
                chunk = await file.read_chunk()  # 默认是8192个字节。
                if not chunk:
                    break
                size += len(chunk)
                f.write(chunk)
        data = pd.read_csv(fileName, encoding='gbk')
        orderList = await getOrderIdListFromFile(data['订单号'])
        score_card = load_model_re(data)
        await removeFile(fileName)
        return web.json_response(
            toResponse(code=ConstValues.CODE_SUCCESS, message=ConstValues.MESSAGE_SUCCESS,
                       data=score_card))




    except:
        f = open('异常日志.txt', 'a')
        traceback.print_exc(file=f)
        f.flush()
        f.close()
        return web.json_response(
            toResponse(code=ConstValues.CODE_ERROR, message=ConstValues.MESSAGE_ERROR,
                       data=orderList))

async def removeFile(fileName):
    os.remove(fileName)


async def getOrderIdListFromJson(items):
    data = []
    for item in items:
        dict = {"orderId": item["订单号"]}
        data.append(dict)
    return data


async def getOrderIdListFromFile(orderIds):
    data = []
    for item in orderIds:
        if isinstance(item, str):
            dict = {"orderId", item}
            data.append(dict)
    return data
